package com.gzk.user.controller;

import com.gzk.basic.exception.BusinessException;
import com.gzk.basic.util.AjaxResult;
import com.gzk.basic.util.PageList;
import com.gzk.user.domain.User;
import com.gzk.user.dto.UserDto;
import com.gzk.user.query.UserQuery;
import com.gzk.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口",description = "用户接口详细描述")
public class UserController {

    //注入
    @Autowired
    private IUserService userService;

    @GetMapping("/{id}")
    public User getById(@PathVariable("id") Long id){
        return userService.queryById(id);
    }

    @GetMapping("/list")
    public List<User> getAll(){
        return userService.queryAll();
    }

    @PostMapping("/page")
    public PageList<User> pageQuery(@RequestBody UserQuery query){
        return userService.queryPage(query);
    }

    @ApiOperation(value = "用户添加或修改",notes = "如果有id就是修改否则就是添加")
    @PostMapping("/save")
    public AjaxResult saveOrUpdate(@RequestBody User user){
        try {
            //判断
            if(user.getId() == null){
                //增加
                userService.add(user);
            }else {
                //修改
                userService.update(user);
            }
            //成功
            return AjaxResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            //失败
            return AjaxResult.ok().setSuccess(false).setMessage("系统繁忙！！");
        }
    }

    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            userService.remove(id);
            return AjaxResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            //失败
            return AjaxResult.ok().setSuccess(false).setMessage("系统繁忙！！");
        }
    }

    @PatchMapping("/batch")
    public AjaxResult deleteMany(@RequestBody List<Long> ids){
        try {
            userService.removeMany(ids);
            return AjaxResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            //失败
            return AjaxResult.ok().setSuccess(false).setMessage("系统繁忙！！");
        }
    }

    @PostMapping("/register")
    public AjaxResult register(@RequestBody UserDto userDto){
        try {
            userService.register(userDto);
            return AjaxResult.ok();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.ok().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ok().setSuccess(false).setMessage("系统繁忙!!!");
        }
    }
}
